<template>
    <div>
        <el-container style="height: 700px; border: 1px solid #eee">
             <el-header style="font-size: 40px; background-color: rgb(238,241,246);">学生成绩管理系统</el-header>
                <el-container>
                    <el-aside width="200px">
                      <el-menu :default-openeds="['1', '3']">
              <el-submenu index="1">
                <template slot="title"><i class="el-icon-menu"></i>专业</template>
                <el-menu-item-group>
                  <template slot="title">网安23级</template>
                  <el-menu-item index="1-1">
                    <router-link to="/students" style="text-decoration: none;">学生管理</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-2">
                    <router-link to="/score" style="text-decoration: none;">学生成绩</router-link>
                  </el-menu-item>
                </el-menu-item-group>
              </el-submenu>
              <el-submenu index="2">
                <template slot="title"><i class="el-icon-message"></i>班级管理</template>
                <el-menu-item-group>
                  <template slot="title">班级管理</template>
                  <el-menu-item index="2-1">
                    <router-link to="/class" style="text-decoration: none;">班级管理</router-link>
                  </el-menu-item>
                </el-menu-item-group>
              </el-submenu>
              <el-submenu index="3">
                <template slot="title"><i class="el-icon-message"></i>班级信息管理</template>
                <el-menu-item-group>
                              <template slot="title">网安2311</template>
                              <el-menu-item index="3-1" @click="fetchStudentsByDeptId('2311')">学生管理</el-menu-item>
                              <el-menu-item index="3-2" @click="fetchScoreByDeptId('2311')">学生成绩</el-menu-item>
                          </el-menu-item-group>
                          <el-menu-item-group title="网安2312">
                              <el-menu-item index="3-3" @click="fetchStudentsByDeptId('2312')">学生管理</el-menu-item>
                              <el-menu-item index="3-4" @click="fetchScoreByDeptId('2312')">学生成绩</el-menu-item>
                          </el-menu-item-group>
                          <el-menu-item-group title="网安2313">
                              <el-menu-item index="3-5" @click="fetchStudentsByDeptId('2313')">学生管理</el-menu-item>
                              <el-menu-item index="3-6" @click="fetchScoreByDeptId('2313')">学生成绩</el-menu-item>
                          </el-menu-item-group>
              </el-submenu>
            </el-menu>
                  </el-aside>
                    <el-main>
                      <el-form :inline="true" :model="searchForm" class="search-form">
                        <el-form-item label="学号">
                          <el-input v-model="searchForm.studentId"></el-input>
                        </el-form-item>
                        <el-form-item label="姓名">
                          <el-input v-model="searchForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="性别">
                          <el-select v-model="searchForm.gender">
                            <el-option label="男" value="1"></el-option>
                            <el-option label="女" value="2"></el-option>
                            <el-option label="全部" value=""></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" @click="handleSearch">搜索</el-button>
                        </el-form-item>
                      </el-form>

                      <div style="display: flex; justify-content: flex-end;">
                         <el-button type="primary" @click="handleAdd">新增学生</el-button>
                      </div>

                      <el-table :data="paginatedData" border >
                        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
                            <el-table-column prop="studentId" label="学号" width="140"></el-table-column>
                            <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                            <el-table-column  label="性别">
                              <template  slot-scope="scope">
                                  {{ scope.row.gender == 1?'男':'女' }}
                              </template>
                            </el-table-column>
                            <el-table-column prop="birth" label="出生日期"></el-table-column>
                            <el-table-column prop="deptId" label="班级"></el-table-column>
                            <el-table-column label="操作">
                              <template slot-scope="scope">
                                <el-button
                                  size="mini"
                                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                <el-button
                                  size="mini"
                                  type="danger"
                                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                              </template>
                          </el-table-column>
                          </el-table>

                          <el-pagination 
                                background
                                layout="prev, pager, next"
                                :total="totalData"
                                :page-size="pageSize"
                                :current-page="currentPage"
                                :hide-on-single-page="true"
                                @current-change="handlePageChange">
                              </el-pagination>

                              <el-dialog :visible.sync="addDialogVisible" title="新增学生">
                                <el-form :model="newEmployee" label-width="80px">
                                  <el-form-item label="姓名">
                                    <el-input v-model="newEmployee.name"></el-input>
                                  </el-form-item>
                                  <el-form-item label="性别">
                                    <el-select v-model="newEmployee.gender">
                                      <el-option label="男" value="1"></el-option>
                                      <el-option label="女" value="2"></el-option>
                                    </el-select>
                                  </el-form-item>
                                  <el-form-item label="出生日期">
                                    <el-date-picker v-model="newEmployee.birth" type="date"></el-date-picker>
                                  </el-form-item>
                                  <el-form-item label="班级">
                                    <el-input v-model="newEmployee.deptId"></el-input>
                                  </el-form-item>
                                  <el-form-item>
                                    <el-button type="primary" @click="submitAdd">保存</el-button>
                                    <el-button @click="addDialogVisible = false">取消</el-button>
                                  </el-form-item>
                                </el-form>
                              </el-dialog>
                              <el-dialog :visible.sync="editDialogVisible" title="编辑学生">
                              <el-form :model="editEmployee" label-width="80px">
                                <el-form-item label="学号">
                                  <el-input v-model="editEmployee.studentId" disabled></el-input>
                                </el-form-item>
                                <el-form-item label="姓名">
                                  <el-input v-model="editEmployee.name"></el-input>
                                </el-form-item>
                                <el-form-item label="性别">
                                  <el-select v-model="editEmployee.gender">
                                    <el-option label="男" value="1"></el-option>
                                    <el-option label="女" value="2"></el-option>
                                  </el-select>
                                </el-form-item>
                                <el-form-item label="出生日期">
                                  <el-date-picker v-model="editEmployee.birth" type="date"></el-date-picker>
                                </el-form-item>
                                <el-form-item label="班级">
                                  <el-input v-model="editEmployee.deptId"></el-input>
                                </el-form-item>
                                <el-form-item>
                                  <el-button type="primary" @click="submitEdit">保存</el-button>
                                  <el-button @click="editDialogVisible = false">取消</el-button>
                                </el-form-item>
                              </el-form>
                            </el-dialog>
                  </el-main>
                </el-container>
        </el-container>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data(){
      return{
        tableData:[],
        deleteList:[],
        totalData: 0, // 总数据量
        pageSize : 10,//展示数据量
        currentPage: 1, // 当前页
        searchForm: {
        studentId:null,
        name: '',
        gender: '',
      },
      addDialogVisible: false, // 新增学生对话框的可见性
      newEmployee: {
        studentId: '',
        name: '',
        gender: '',
        birth: '',
        deptId: ''
      },
      editDialogVisible: false, // 编辑学生对话框的可见性
      editEmployee: {
        studentId: '',
        name: '',
        gender: '',
        birth: '',
        deptId: ''
      }
      }
    },
    mounted(){
      this.handlePageChange(1)
    },
    computed: {
    paginatedData() {
      return this.tableData;
    }
  },
  
    methods:{
      async handleSearch() {
      this.currentPage = 1;
      await this.fetchSearchData();
      },
      async handlePageChange(newpage) {
      this.currentPage = newpage;
      try {
                await this.fetchData();
                console.log('当前选中的页码是,' + newpage);
            } catch (error) {
                alert('请求失败：', error);
                alert('请求失败，请检查网络或联系管理员');
            }
    },
    async fetchData() {
            try {
                const response = await axios.get('http://localhost:8080/allStudents', {
                    params: {
                      page: this.currentPage,
                      pageSize: this.pageSize,
                    }
                });
                const result = response.data;
                if (result.code === 1 && result.msg === "success" && result.data) {
                    // 检查 result.data 是否存在
                    this.tableData = result.data.rows;
                    this.totalData = result.data.total;
                } else {
                    console.error('请求不成功：', result.msg);
                    alert('请求不成功，请检查网络或联系管理员');
                }
            } catch (error) {
                console.error('请求失败：', error);
                alert('请求失败，请检查网络或联系管理员');
            }
        },
        async handleDelete(index, row) {
            try {
              // 假设你使用 DELETE 方法删除数据，这里需要将 id 发送到后端
              await axios.delete(`http://localhost:8080/student/${row.studentId}`);
              // 从 tableData 中移除被删除的行
              this.tableData.splice(index, 1);
              alert('删除成功');
            } catch (error) {
              console.error('删除失败：', error);
              alert('删除失败，请检查网络或联系管理员');
            }
    },
    handleAdd() {
      // 打开新增员工对话框
      this.addDialogVisible = true;
    },
    async submitAdd() {
      try {
        const response = await axios.post('http://localhost:8080/students', this.newEmployee);
        const result = response.data;
        if (result.code === 1 && result.msg === "success") {
          // 关闭对话框
          this.addDialogVisible = false;
          // 重新加载数据
          this.handlePageChange(this.currentPage);
          alert('新增成功');
        } else {
          if(result.msg === "该学生 ID 已被使用，请使用其他 ID。"){
            alert('该学号已存在,请重新输入学生信息')
          }else{
          alert('新增不成功，请检查网络或联系管理员');
          }
        }
      } catch (error) {
        console.error('新增失败：', error);
        alert('新增失败，请检查网络或联系管理员');
      }
    },
    handleEdit(index, row) {
      // 打开编辑员工对话框并加载数据
      this.editDialogVisible = true;
      this.editEmployee = {...row};
      // 根据 id 获取学生的详细信息，此处使用后端的 GET 请求接口 /students/{id}
      this.fetchEditData(row.studentId);
    },
    async fetchEditData(studentId) {
      try {
        const response = await axios.get(`http://localhost:8080/students/${studentId}`);
        const result = response.data;
        if (result.code === 1 && result.msg === "success" && result.data) {
          // 检查 result.data 是否存在
          this.editEmployee = result.data;
        } else {
          console.error('获取学生信息不成功：', result.msg);
          alert('获取学生信息不成功');
        }
      } catch (error) {
        console.error('获取学生信息失败：', error);
       alert('获取学生信息失败，请检查网络或联系管理员');
      }
    },
    async fetchSearchData() {
      try {
        const response = await axios.get('http://localhost:8080/findStudents', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            studentId: this.searchForm.studentId,
            name: this.searchForm.name,
            gender: this.searchForm.gender === ''? null : this.searchForm.gender,
            deptId: this.searchForm.studentId === parseInt(this.searchForm.deptId)
          }
        });
        const result = response.data;
        if (result.code === 1 && result.msg === "success") {
              if (result.data) {
                this.tableData = result.data.rows;
                this.totalData = result.data.total;
              } else {
                alert("未找到符合条件的学生");
              }
        }else {
          console.error('搜索请求不成功：', result.msg);
          alert('搜索请求不成功，请检查网络或联系管理员');
        }
      } catch (error) {
        console.error('搜索请求失败：', error);
        alert('搜索请求失败，请检查网络或联系管理员');
      }
    },
    async submitEdit() {
      try {
        const response = await axios.put(`http://localhost:8080/students`, this.editEmployee);
        const result = response.data;
        if (result.code === 1 && result.msg === "success") {
          // 关闭对话框
          this.editDialogVisible = false;
          // 重新加载数据，假设 handlePageChange 方法已经实现
          this.handlePageChange(this.currentPage);
          alert('编辑成功');
        } else {
          console.error('编辑不成功：', result.msg);
          alert('编辑不成功，请检查网络或联系管理员');
        }
      } catch (error) {
        console.error('编辑失败：', error);
        alert('编辑失败，请检查网络或联系管理员');
      }
    },
    convertToInteger(value) {
      if (value === '' || value === null) {
        return null;
      }
      const intValue = parseInt(value);
      if (isNaN(intValue)) {
        alert('班级编号必须是有效的数字');
        return null;
      }
      return intValue;
    },
    async fetchStudentsByDeptId(deptId) {
      let classId =deptId;
      this.$router.push(`/${classId}/students`);

      }, 
      async fetchScoreByDeptId(deptId) {

        let classId = deptId;
        this.$router.push(`/${classId}/score`);

      },
      navigateTo(route) {
          this.$router.push(route);
      }
  }
}
</script>

<style>

</style>